/**
 * 获取菜单列表
 * @url admin/system/menu/sys/getList
 * @description 获取菜单列表
 */
module.exports = {
	main: async (event) => {
		let { data = {}, userInfo, util, filterResponse, originalParam } = event;
		let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
		let { uid } = data;
		let res = { code: 0, msg: '' };
		
		// 业务逻辑开始-----------------------------------------------------------
		let { keyword = '' } = data;
		
		// 构建查询条件
		let where = {};
		if (keyword) {
			where = _.or([
				{ name: new RegExp(keyword, 'i') },
				{ menu_id: new RegExp(keyword, 'i') },
				{ url: new RegExp(keyword, 'i') }
			]);
		}
		
		// 查询菜单列表
		let menuRes = await db.collection('opendb-admin-menus')
			.where(where)
			.orderBy('sort', 'asc')
			.orderBy('create_date', 'asc')
			.get();
		
		// 处理菜单层级
		const getDepth = (menus, id, depth = 0) => {
			const menu = menus.find(m => m.menu_id === id);
			if (menu && menu.parent_id) {
				return 1 + getDepth(menus, menu.parent_id, depth);
			}
			return depth;
		};
		
		menuRes.data.forEach(item => {
			const depth = getDepth(menuRes.data, item.menu_id);
			item.depth = depth;
			item.name_display = '　'.repeat(depth) + (depth > 0 ? '|-' : '') + item.name;
		});
		
		res.data = {
			list: menuRes.data
		};
		
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}

